export let createDialog = (url: string, config: any): Promise<Window> => {
  return new Promise((resolve, reject) => {
    let windowProxy = window.open(url, "_blank", JSON.stringify(config)) as Window;
    let readyHandler = (e: any) => {
      let msg = e.data;
      if (msg["msgName"] === `__dialogReady`) {
        // 子窗口已经成功创建 可以给父窗口进行resolve了
        //   在resolve之前需要将之前的Message事件监听函数移除 避免内存泄露(用户每打开一个子窗口，就会注册一个Message事件)
        window.removeEventListener("message", readyHandler);
        resolve(windowProxy);
      }
    };
    window.addEventListener("message", readyHandler);
  });
};

/**
 * 供子窗口服务  子窗口完成对应的逻辑后通过这个方法告知父窗口已经加载成功
 */
export let dialogReady = () => {
  let msg = { msgName: `__dialogReady` };
  // 向父窗口发送一个消息
  window.opener.postMessage(msg);
};
